<template>
  <div class="m-2 mr-0 overflow-hidden bg-white classify-tree" v-dragSize style="width: 300px;">
    <BasicTree
title="数据类型" treeWrapperClassName="h-[calc(100%-35px)] overflow-auto" :clickRowToExpand="false"
      :treeHeaderAction="treeHeaderAction" :treeData="treeData" :actionList="actionList"
      :fieldNames="{ key: 'classifyId', title: 'classifyName' }" @select="handleSelect" search 
      :filterFn="filterFn"/>
    <ClassifyTypeModal @register="registerTypeModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref, h, createVNode } from 'vue';
import { getClassifyTree, deleteClassify, exportClassifyTree  } from '@/api/collection/classify';
import { BasicTree, ContextMenuItem, TreeItem } from '@/components/Tree';
import ClassifyTypeModal from './ClassifyTypeModal.vue';
import { useModal } from '@/components/Modal/index';
import { TreeActionItem } from '@/components/Tree/index';
import EditOutlined from '@ant-design/icons-vue/lib/icons/EditOutlined';
import DeleteOutlined from '@ant-design/icons-vue/lib/icons/DeleteOutlined';
import PlusOutlined from '@ant-design/icons-vue/lib/icons/PlusOutlined'
import { DownloadOutlined } from '@ant-design/icons-vue'
import { getClassifyDetail } from '@/api/collection/classify/index';
import { Modal } from 'ant-design-vue';
import { downloadByData } from '@/utils/file/download';

const [registerTypeModal, { openModal: openClassifyTypeModal }] = useModal()

const emit = defineEmits(['select']);

const treeData = ref<TreeItem[]>([]);

async function fetch() {
  const res = await getClassifyTree({})
  res.length && handleSelect([res[0].classifyId])
  const formateRes = addCopyName(res)
  treeData.value = (formateRes) as unknown as TreeItem[];
}

function addCopyName(arr) {
  return arr.map(item => {
    if (item.children && item.children.length) {
      addCopyName(item.children)
    }
    item.classifyNameCopy = item.classifyName
    return item
  })
}

const treeHeaderAction = () => {
  openClassifyTypeModal(true, {
    isUpdate: false,
  });
};
const filterFn = (searchValue, node) => {
  console.log(node, 'node')
  return node['classifyId']?.includes(searchValue)
}
const actionList: TreeActionItem[] = [
  {
    render: (node) => {
      return h(PlusOutlined, {
        class: 'ml-2',
        onClick: (e) => {
          e.stopPropagation()
          handleAddChildren(node)
        },
      });
    },
  },
  {
    render: (node) => {
      return h(EditOutlined, {
        class: 'ml-2',
        onClick: (e) => {
          e.stopPropagation()
          handleEdit(node)
        },
      });
    },
  },
  {
    render: (node) => {
      return h(DeleteOutlined, {
        class: 'ml-2',
        onClick: (e) => {
          e.stopPropagation()
          showConfirm(node)
        },
      });
    },
  },
  {
    render: (node) => {
      return h(DownloadOutlined, {
        class: 'ml-2 mr-2',
        onClick: (e) => {
          e.stopPropagation()
          handleExport(node)
        },
      });
    },
  }
];
const handleExport = async (node) => {
  const params = {
    classifyId: node.classifyId
  }
  const { data, headers } = await exportClassifyTree(params)
  let contentDisposition = decodeURIComponent(headers["content-disposition"])
  const filenameMatch = contentDisposition.match(/filename\*=UTF-8''(.+)|filename="(.+)"|filename=(.+)/)
  const fileName = filenameMatch[1] || filenameMatch[2] || filenameMatch[3]
  downloadByData(data, fileName)
}
const showConfirm = (node) => {
  Modal.confirm({
    title: '确认删除该设备类型?',
    icon: createVNode(DeleteOutlined),
    onOk() {
      handleDelete(node);
    },
    onCancel() { },
  });
};

const handleDelete = async (node) => {
  await deleteClassify({ classifyId: node.classifyId })
  fetch()
}

async function handleEdit(record: Recordable) {
  const ret = await getClassifyDetail({ classifyId: record.classifyId })
  console.log(ret)
  openClassifyTypeModal(true, {
    ret,
    isUpdate: true,
  })
}

async function handleAddChildren(record: Recordable) {
  openClassifyTypeModal(true, {
    ret: record,
    isUpdate: false,
    addChildren: true,
  })
}

function handleSuccess() {
  fetch()
}

function handleSelect(keys) {
  emit('select', keys[0]);
}

onMounted(() => {
  fetch();
});

</script>
